package front_message_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type MessageSendReq struct {
	SendUserID uint   `json:"send_user_id"` // 发送人id
	RevUserID  uint   `json:"rev_user_id"`  // 接收人id
	Content    string `json:"content"`      // 消息内容
}

// 发送消息
func (MessageApi) MessageSend(c *gin.Context) {
	var request MessageSendReq
	if err := c.ShouldBindJSON(&request); err != nil {
		logrus.Error(err)
		panic(err)
	}
	// 查询一下接收人和发送人是否存在
	var userModelList []models.UserModel
	idList := []uint{request.SendUserID, request.RevUserID}
	affected := global.DB.Find(&userModelList, idList).RowsAffected
	if affected != 2 {
		panic("发送人或接收人信息不存在")
	}
	var sendUserModel, revUserModel models.UserModel
	for _, model := range userModelList {
		if model.ID == request.SendUserID {
			sendUserModel = model
		} else {
			revUserModel = model
		}
	}
	err := global.DB.Create(&models.MessageModel{
		SendUserID:       sendUserModel.ID,
		SendUserNickName: sendUserModel.NickName,
		SendUserAvatar:   sendUserModel.Avatar,
		RevUserID:        revUserModel.ID,
		RevUserNickName:  revUserModel.NickName,
		RevUserAvatar:    revUserModel.Avatar,
		IsRead:           false,
		Content:          request.Content,
	}).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	res.Ok("消息发送成功", true, c)
}
